package tree;

import expression.Expression;

import java.util.LinkedList;
import java.util.List;

/**
 * 树形节点
 */
public class Node {
    private String text;
    private String fullText;
    private Object value;
    private Node parent;
    private Expression exp;
    private List<Node> children = new LinkedList<Node>();

    public Node() {}

    public Node(String text, String fullText, Object value, Node parent, Expression exp) {
        this.text = text;
        this.fullText = fullText;
        this.value = value;
        this.parent = parent;
        this.exp = exp;
    }

    /**
     * 获取结果
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public Object getRes(Object obj) throws Exception {
        if(null != value) {
            return value;
        }
        //
        if(null == exp) {
            return children.get(0).getRes(obj);
        }
        //
        Object[] params = new Object[children.size() + 1];
        int i = 0;
        params[i] = obj;
        for(Node node : children) {
            params[++i] = node.getRes(obj);
        }
        //
        return exp.exec(params);
    }

    public void addChild(Node child) {
        children.add(child);
        child.setParent(this);
    }

    public Node getRoot() {
        Node res = this;
        while(null != res.getParent()) {
            res = res.getParent();
        }
        return res;
    }

    public Expression getExp() {
        return exp;
    }

    public void setExp(Expression exp) {
        this.exp = exp;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }

    public List<Node> getChildren() {
        return children;
    }

    public void setChildren(List<Node> children) {
        children = new LinkedList<Node>();
        for(Node child : children) {
            addChild(child);
        }
    }

    public String getFullText() {
        return fullText;
    }

    public void setFullText(String fullText) {
        this.fullText = fullText;
    }
}
